今天要學的是Java 如何去控制我們的Java程式
有時會因應需求改變程式執行的方向,就稱為選擇結構
有時則是某些程式片段需要重複執行很多次,就稱為重複結構
然而我們的選擇結構和重複結構需要透過各種控制敘述去達成
我們Java的控制敘述大致上分成三種 => 選擇敘述、重複敘述、分支敘述
double h = 178.9;
if(h > 170){
System.out.println("好高ㄟ");
}
Scanner scn = new Scanner(System.in);
int avg = 5;
int num = scn.nextInt();
if (num >= avg) {
System.out.println("讚喔!!");
} else {
System.out.println("加油~");
}
Scanner scn = new Scanner(System.in);
int secret = 55;
int guess = scn.nextInt();
if (guess > secret){
System.out.println("lower");
} else if(guess < secret){
System.out.println("higher");
} else {
System.out.println("Great!!");
}
Scanner scn = new Scanner(System.in);
int num1, num2, num3, max;
System.out.println("請輸入三個數: ");
num1 = scn.nextInt();
num2 = scn.nextInt();
num3 = scn.nextInt();
if(num1 > num2){
if (num1 > num3){
max = num1;
}else {
max = num3;
}
} else {
if (num2 > num3){
max = num2;
} else {
max = num3;
}
}
System.out.println("Max is " + max);
Scanner scn = new Scanner(System.in);
System.out.print("Your Grade: ");
int score = scn.nextInt();
int level = score / 10;
switch (level) {
case 10:
case 9:
case 8:
System.out.print(" => A");
break;
case 7:
System.out.print(" => B");
break;
case 6:
System.out.print(" => C");
break;
default:
System.out.print(" => F");
}
可以用 -> 取代 :
int num = 3;
String numString = switch (num){
case 1 -> "一";
case 2 -> "二";
case 3 -> "三";
case 4 -> "四";
default -> "錯誤";
};
System.out.println(numString);
以上幾個功能就是符合條件的狀況下,能夠去重複執行相同Java程式
int sum = 0;
for (int i = 1; i <= 10; i++){
sum += i;
}
System.out.println("1 + 2 + 3 + ... + 10 = " + sum);
int sum = 0;
for (int i = 1; i < 10; i++){
for(int j = 1; j < 10; j++){
System.out.print(j + " * " + i + " = " +i * j + "\t");
}
System.out.println();
}
int sum = 10;
int count = 0;
while(sum > 0){
sum /= 3;
count += 1;
}
System.out.println("跑了幾次while: " + count);
int sum = 20;
int count1 = 0;
int count2 = 0;
while(sum > 0){
sum -= 5;
while(sum > 5){
sum -= 3;
count2 += 1;
}
count1 += 1;
}
System.out.println("跑了幾次外層while: " + count1);
System.out.println("跑了幾次內層while: " + count2);
和while差異的地方是
while是先判斷條件再去做
do~while則是先做了再去判斷條件
所以do~while至少會執行一次
Scanner scn = new Scanner(System.in);
int num1 = scn.nextInt();
int num2 = scn.nextInt();
String func;
System.out.println("*****選單*****");
System.out.println("\tA: 加法");
System.out.println("\tB: 減法");
System.out.println("\tC: 離開");
do{
func = scn.next().toUpperCase();
switch (func){
case "A" -> System.out.println("num1 + num2 = " + (num1+num2));
case "B" -> System.out.println("num1 - num2 = " + (num1-num2));
}
}while(!func.equals("C"));
for (int i = 0; i < 10; i++){
System.out.println(i);
if (i == 5){
break;
}
}
for (int i = 0; i < 10; i++){
System.out.println(i);
if (i == 5){
continue;
}
}